package data;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import android.app.Activity;

/**
 * This class checks to see if the credentials of an account are correct
 * 
 * @author Pooja
 */
public class AccountCorrectCredentials extends DBBooleanTask<Account> {

	/**
	 * Create an object that checks if the database has an account matching the
	 * acct credentials
	 * 
	 * @param activity
	 *            - the activity for the loading bar
	 * @param acct
	 *            - the account to check the credentials
	 * @throws DBInterfaceError
	 */
	public AccountCorrectCredentials(Activity activity, Account acct)
			throws DBInterfaceError {
		super(activity, acct);
	}

	@Override
	/**
	 * actually checks if the account exists or not
	 * @param account - the account to check
	 * @returns true if it exists, else false
	 */
	protected boolean task(Account account) {

		boolean correctCreds = false;

		System.out.println("yooo 2222");

		// try {
		// if (new AccountExists(activity, account).getResult()){
		System.out.println("fasdfdasfdasfdasfasdfdasf");
		PreparedStatement correctCredentialsQuery;
		ResultSet set;
		//
		try {
			correctCredentialsQuery = conn
					.prepareStatement("SELECT loginTimes FROM account WHERE accountName = ? AND password = ?");
			correctCredentialsQuery.setString(1, account.getAccountName());
			correctCredentialsQuery.setString(2, account.getPassword());
			set = correctCredentialsQuery.executeQuery();
			System.out.println("panda");
			int newLoginTimes;
			if (set.next()) { // password and user name match
				System.out.println("yooo");
				newLoginTimes = 0;
				correctCreds = true;

			} else { // username matches, password does not
				System.out.println("USA USA USA USA USA USA");
				correctCredentialsQuery = conn
						.prepareStatement("SELECT loginTimes FROM account WHERE accountName = ?");
				correctCredentialsQuery.setString(1, account.getAccountName());
				set = correctCredentialsQuery.executeQuery();
				set.next();
				newLoginTimes = set.getInt("loginTimes") + 1;
				System.out.println("USSR USSR " + newLoginTimes);
			}

			correctCredentialsQuery = conn
					.prepareStatement("UPDATE account SET loginTimes = ? WHERE accountName = ?");
			correctCredentialsQuery.setInt(1, newLoginTimes);
			correctCredentialsQuery.setString(2, account.getAccountName());
			correctCredentialsQuery.execute();

			correctCredentialsQuery = conn
					.prepareStatement("UPDATE account SET locked = ? WHERE loginTimes >= 3");
			correctCredentialsQuery.setBoolean(1, true);
			correctCredentialsQuery.execute();

		} catch (SQLException e) {
			e.printStackTrace();
		}

		// }
		// } catch (DBInterfaceError e) {
		// e.printStackTrace();
		// System.out.println("murica");
		// }

		return correctCreds;
	}

}
